package Res;

import org.json.JSONException;
import org.json.JSONObject;

import Clock.Clock;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import Scene.Renderable;

import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
public class StaticImgResource  extends Resource 
{
	public TextureRegion res;

	public boolean bVis_ = true;
	// normally, we define the anchor as the center of a static image.
	public int nOffsetX = 0;
	public int nOffsetY = 0;
	
	// the texture maybe a combination of many small textures
	public int nTextureBeginX = 0;
	public int nTextureBeginY = 0;
	
	public StaticImgResource()
	{
		nWidth = 0;
		nHeight = 0;
	}
	

	public void LoadRes(String fileName)
	{
		FileHandle hFile = Gdx.files.internal(fileName);
		String data = hFile.readString();
		
		try
		{
			JSONObject json = new JSONObject(data);
			LoadRes(json);
		}
		catch(JSONException e)
		{
		
		}		
	}	
	
	public void LoadRes(JSONObject jsonComp)
	{		
		try
		{
			nWidth = jsonComp.getInt("w");
			nHeight = jsonComp.getInt("h");
			nOffsetX = jsonComp.getInt("offx");
			nOffsetY = jsonComp.getInt("offy");
			
			if (jsonComp.has("bx"))
			{
				nTextureBeginX = jsonComp.getInt("bx");				
			}
			
			if (jsonComp.has("by"))
			{
				nTextureBeginY = jsonComp.getInt("by");				
			}
			
			String texName = jsonComp.getString("file");
			
			Texture texture = TextureMgr.GetInst().GetTexture(texName);
			res = new TextureRegion(texture, nTextureBeginX, nTextureBeginY, nWidth, nHeight);

		}
		catch(JSONException e)
		{
		
		}		
	}	
	
	public void SetVisible(boolean bVis)
	{
		bVis_ = bVis;
	}
	
	public void Update(Clock clock)
	{ 
	}
	
	public void Render(SpriteBatch spriteBatch, Matrix4 matrix)
	{		 
		int width = res.getRegionWidth();
		if (width < 0) width = -width;
		
		int height = res.getRegionHeight();
		if (height < 0) height = -height;
		Matrix4 matrixOut = matrix.cpy();
		Matrix4 matrixTrans = new Matrix4();
		matrixTrans.translate(-width / 2, -height/ 2, 0);
		matrixTrans.translate(-nOffsetX, -nOffsetY, 0);

		matrixOut.mul(matrixTrans);
		
		spriteBatch.setTransformMatrix(matrixOut);
		spriteBatch.draw( res, 0, 0, width, height);
	}
}
